﻿// Copyright (C) Jari Hautio <jari.hautio@iki.fi> 2009. Licensed under GPLv2. See LICENSE.txt in solution folder.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace RyijyApp
{
    public partial class PaletteMgrForm : Form
    {
        List<CustomPalette> paletteList = new List<CustomPalette>();
        internal List<CustomPalette> UserPaletteList { get { return paletteList; } set { paletteList = value; LoadPaletteList(); } }

        List<CustomPalette> systemPaletteList = new List<CustomPalette>();
        internal List<CustomPalette> SystemPaletteList { get { return systemPaletteList; } set { systemPaletteList = value; LoadPaletteList(); } }

        private CustomPalette CurrentPalette { get { return customPaletteBindingSource.Current as CustomPalette; } }

        private List<CustomPalette> AllPaletteList
        {
            get
            {
                List<CustomPalette> l = new List<CustomPalette>(systemPaletteList);
                l.AddRange(UserPaletteList);
                return l;
            }
        }
        public PaletteMgrForm()
        {
            InitializeComponent();
        }

        void LoadPaletteList()
        {
            customPaletteBindingSource.DataSource = paletteList;
        }

        private void PaletteMgrForm_Load(object sender, EventArgs e)
        {
            LoadPaletteList();
        }

        private string CreateNewName(string body)
        {
            List<string> items = new List<string>();

            foreach (CustomPalette p in paletteList)
            {
                items.Add(p.PaletteName);
            }
            string text = body;
            int id = 2;
            while (items.Contains(text))
            {
                text = body + id.ToString();
                id++;
            }
            return text;
        }
        string GetFilename(string paletteName)
        {
            string path = "";
            if (RyijyApp.Properties.Settings.Default.Standalone)
            {
                path = Application.StartupPath;
            }
            else
            {
                path = Application.UserAppDataPath;
                int pos = path.LastIndexOf('\\');
                path = path.Substring(0, pos);
            }
            return path + "\\" + paletteName + "_palette.txt";
        }
        private void buttonNew_Click(object sender, EventArgs e)
        {
            CustomPalette p = new CustomPalette();
            p.UserPalette = true;
            p.PaletteName = CreateNewName(RyijyApp.Properties.Resources.PaletteNewName);

            PaletteForm pf = new PaletteForm();
            pf.PaletteList = AllPaletteList;
            pf.TargetPalette = p;
            if (pf.ShowDialog() == DialogResult.OK)
            {
                customPaletteBindingSource.Add(p);
                p.Save(GetFilename(p.PaletteName));
            }
        }

        private void buttonEdit_Click(object sender, EventArgs e)
        {

            CustomPalette selected = CurrentPalette;
            if (selected == null) return;

            PaletteForm pf = new PaletteForm();
            pf.PaletteList = AllPaletteList;
            pf.TargetPalette = new CustomPalette(selected);
            if (pf.ShowDialog() == DialogResult.OK)
            {
                // copy colors
                selected.Colors = pf.TargetPalette.Colors;
                selected.PaletteName = pf.TargetPalette.PaletteName;
                string newName = GetFilename(selected.PaletteName);
                if (newName != selected.FileName)
                    System.IO.File.Move(selected.FileName, newName);
                selected.FileName = newName;
                selected.Save();
                customPaletteBindingSource.ResetBindings(false);
            }

        }

        void UpdateButtons()
        {
            buttonDelete.Enabled = CurrentPalette != null;
            buttonEdit.Enabled   = CurrentPalette != null;
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            CustomPalette p = CurrentPalette;
            if (p == null) return;

            // Show delete confirmation only if palette contains colors
            if (buttonDelete.Tag != null && p.Colors.Count > 0)
            {
                try
                {
                    string msg = string.Format(RyijyApp.Properties.Resources.PaletteConfirmDelete, p.PaletteName);
                    if (MessageBox.Show(msg, this.Text, MessageBoxButtons.YesNo) == DialogResult.No)
                        return;
                }
                catch (Exception)
                {
                }
            }
            try
            {
                customPaletteBindingSource.Remove(p);
                if (p.FileName != "")
                {
                    System.IO.File.Delete(p.FileName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            UpdateButtons();
        }

        private void buttonRename_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedCells.Count>0)
                dataGridView1.BeginEdit(false);
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                CustomPalette p = dataGridView1.Rows[e.RowIndex].DataBoundItem as CustomPalette;
                if (p != null)
                {
                    string newName = GetFilename(p.PaletteName);
                    if (newName != p.FileName)
                    {
                        System.IO.File.Move(p.FileName, newName);
                        p.FileName = newName;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            dataGridView1.Rows[e.RowIndex].ErrorText = "";
        }

        private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
        {
            string nokey = "\\/:*?\"<>|";
            if (nokey.Contains(e.KeyChar.ToString()))
                e.Handled = true;

        }

        private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
        }

        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            e.Control.KeyPress += new KeyPressEventHandler(dataGridView1_KeyPress);
            e.Control.Validating += new CancelEventHandler(Control_Validating);
        }

        void Control_Validating(object sender, CancelEventArgs e)
        {
            if (dataGridView1.EditingControl != null)
            {
                string text = dataGridView1.EditingControl.Text;
                foreach (CustomPalette p in paletteList)
                {
                    if (p != CurrentPalette &&
                        p.PaletteName == text)
                    {
                        e.Cancel = true;
                    }

                }
            }
        }

        private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            dataGridView1.Rows[e.RowIndex].ErrorText = "";

            string text = e.FormattedValue.ToString();
            foreach (CustomPalette p in paletteList)
            {
                if (p != CurrentPalette &&
                    p.PaletteName == text)
                {
                    e.Cancel = true;
                    dataGridView1.Rows[e.RowIndex].ErrorText = 
                        RyijyApp.Properties.Resources.PaletteErrorNameExists;
                }

            }

        }

        private void DrawColorBar(Graphics g, Rectangle r, CustomPalette p)
        {
            if (g == null || p == null||r.Width < 1 || p.Colors.Count==0) return;
            using (Bitmap bm = new Bitmap(p.Colors.Count, 1))
            {
                int x = 0;
                foreach (CustomPalette.ColorItem c in p.Colors)
                    bm.SetPixel(x++, 0, c.Color);
                System.Drawing.Drawing2D.InterpolationMode oldmode = g.InterpolationMode;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
                g.DrawImage(bm, r);
                g.InterpolationMode = oldmode;
            }


        }
        private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.ColumnIndex != 0 || e.RowIndex <0)
                return;

            if ((e.PaintParts & DataGridViewPaintParts.Background) != 0)
            {
                e.PaintBackground(e.ClipBounds,(e.State & DataGridViewElementStates.Selected) != 0);
                Rectangle r = e.CellBounds;
                r.Height = 5;
                r.Y = e.CellBounds.Bottom - r.Height;
                
                DrawColorBar(e.Graphics,r,dataGridView1.Rows[e.RowIndex].DataBoundItem as CustomPalette);
                e.Handled = true;
                e.PaintContent(e.ClipBounds);
            }
        }

        private void buttonImport_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    CustomPalette cp = new CustomPalette();
                    if (cp.Load(openFileDialog1.FileName))
                    {
                        // save as new name to user palette folder
                        string newFilename = CreateNewName(GetFilename(cp.PaletteName));                        
                        cp.Save(newFilename);
                        paletteList.Add(cp);
                        customPaletteBindingSource.ResetBindings(false);
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

    }
}
